<!--
  智慧社区管理系统 - 工作管理 - 人员管理
  @author Wu.Liang
  @date 2025-01-30
-->
<template>
  <div class="staff-management">
    <!-- 页面标题 -->
    <el-card class="header-card" shadow="never">
      <div class="page-header">
        <div class="header-title">
          <h2>人员管理</h2>
          <p>管理物业公司员工信息</p>
        </div>
        <div class="header-actions">
          <el-button type="primary" @click="handleAddStaff">
            <el-icon><Plus /></el-icon>
            新增员工
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 搜索筛选区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="queryParams" inline>
        <el-form-item label="搜索关键词">
          <el-input
            v-model="queryParams.keyword"
            placeholder="请输入员工姓名或工号"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="员工状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="全部" :value="null" />
            <el-option label="在职" :value="1" />
            <el-option label="离职" :value="0" />
            <el-option label="待入职" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 状态标签 -->
      <div class="status-tabs">
        <el-button
          v-for="tab in statusTabs"
          :key="tab.value"
          :type="currentStatus === tab.value ? 'primary' : ''"
          size="small"
          @click="handleStatusChange(tab.value)"
        >
          {{ tab.label }}
          <el-badge v-if="tab.count > 0" :value="tab.count" class="status-badge" />
        </el-button>
      </div>
    </el-card>

    <!-- 员工列表卡片区域 -->
    <el-card class="staff-list-card" shadow="never" v-loading="loading">
      <div v-if="staffList.length === 0" class="empty-state">
        <el-empty description="暂无员工数据" />
      </div>
      <div v-else class="staff-grid">
        <div
          v-for="staff in staffList"
          :key="staff.id"
          class="staff-card"
          @click="handleViewDetail(staff)"
        >
          <div class="staff-card-header">
            <div class="staff-avatar">
              <el-avatar :src="staff.avatar" :size="50">
                {{ getAvatarText(staff.realName) }}
              </el-avatar>
            </div>
            <div class="staff-info">
              <div class="staff-name">{{ staff.realName }}</div>
              <div class="staff-status">
                <el-tag :type="getStatusType(staff.status)" size="small">
                  {{ staff.statusText || getStatusText(staff.status) }}
                </el-tag>
              </div>
            </div>
          </div>
          
          <div class="staff-card-body">
            <div class="info-item">
              <span class="label">工号:</span>
              <span class="value">{{ staff.employeeNo || '暂无工号' }}</span>
            </div>
            <div class="info-item">
              <span class="label">手机:</span>
              <span class="value">{{ staff.phone || '暂无手机号' }}</span>
            </div>
            <div class="info-item">
              <span class="label">职位:</span>
              <span class="value">{{ staff.position || '暂无职位' }}</span>
            </div>
            <div class="info-item">
              <span class="label">部门:</span>
              <span class="value">{{ staff.department || '暂无部门' }}</span>
            </div>
            <div class="info-item">
              <span class="label">所属公司:</span>
              <span class="value company-name">{{ staff.propertyCompanyName || '暂无物业公司' }}</span>
            </div>
            <div class="info-item">
              <span class="label">入职日期:</span>
              <span class="value">{{ formatDate(staff.joinDate) }}</span>
            </div>
          </div>
          
          <div class="staff-card-actions">
            <el-button size="small" @click.stop="handleEdit(staff)">编辑</el-button>
            <el-button size="small" type="danger" @click.stop="handleDelete(staff)">删除</el-button>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { workStaffApi, type StaffQueryParams, type StaffVO } from '@/api/work/staff'
import { propertyInfoApi } from '@/api/property/propertyInfo'

// 响应式数据
const loading = ref(false)
const staffList = ref<StaffVO[]>([])
const total = ref(0)
const currentStatus = ref<number | null>(null)

// 查询参数
const queryParams = reactive<StaffQueryParams>({
  pageNum: 1,
  pageSize: 20,
  keyword: '',
  status: null,
  propertyCompanyIds: ''
})

// 状态标签
const statusTabs = ref([
  { label: '全部', value: null, count: 0 },
  { label: '在职', value: 1, count: 0 },
  { label: '离职', value: 0, count: 0 },
  { label: '待入职', value: 2, count: 0 }
])

// 页面加载
onMounted(() => {
  loadStaffList()
})

// 加载员工列表
const loadStaffList = async () => {
  try {
    loading.value = true
    
    // 获取当前用户的物业公司ID列表
    const userPropertyCompanyIds = await getUserPropertyCompanyIds()
    
    // 构建查询参数
    const params = {
      ...queryParams,
      propertyCompanyIds: userPropertyCompanyIds.join(',')
    }
    
    console.log('查询参数:', params)
    
    const response = await workStaffApi.getStaffList(params)
    
    if (response.code === 200 && response.data) {
      staffList.value = response.data.records || []
      total.value = response.data.total || 0
      
      // 更新状态统计
      updateStatusCounts()
      
      console.log('员工列表加载成功:', staffList.value)
    } else {
      ElMessage.error(response.message || '加载员工列表失败')
    }
  } catch (error) {
    console.error('加载员工列表失败:', error)
    ElMessage.error('加载员工列表失败')
  } finally {
    loading.value = false
  }
}

// 获取当前用户的物业公司ID列表
const getUserPropertyCompanyIds = async () => {
  try {
    console.log('获取用户物业公司ID列表')
    const response = await propertyInfoApi.getUserPropertyCompanies()
    
    if (response.code === 200 && response.data) {
      const propertyCompanyIds = response.data.map(item => item.propertyCompanyId)
      console.log('用户关联的物业公司ID列表:', propertyCompanyIds)
      return propertyCompanyIds
    } else {
      console.warn('获取用户物业公司列表失败:', response.message)
      return []
    }
  } catch (error) {
    console.error('获取用户物业公司ID列表失败:', error)
    return []
  }
}

// 更新状态统计
const updateStatusCounts = () => {
  const counts = { all: 0, active: 0, inactive: 0, pending: 0 }
  
  staffList.value.forEach(staff => {
    counts.all++
    if (staff.status === 1) counts.active++
    else if (staff.status === 0) counts.inactive++
    else if (staff.status === 2) counts.pending++
  })
  
  statusTabs.value[0].count = counts.all
  statusTabs.value[1].count = counts.active
  statusTabs.value[2].count = counts.inactive
  statusTabs.value[3].count = counts.pending
}

// 搜索
const handleSearch = () => {
  queryParams.pageNum = 1
  loadStaffList()
}

// 重置
const handleReset = () => {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 20,
    keyword: '',
    status: null,
    propertyCompanyIds: ''
  })
  currentStatus.value = null
  loadStaffList()
}

// 状态切换
const handleStatusChange = (status: number | null) => {
  currentStatus.value = status
  queryParams.status = status
  queryParams.pageNum = 1
  loadStaffList()
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  queryParams.pageSize = size
  queryParams.pageNum = 1
  loadStaffList()
}

// 当前页变化
const handleCurrentChange = (page: number) => {
  queryParams.pageNum = page
  loadStaffList()
}

// 新增员工
const handleAddStaff = () => {
  ElMessage.info('新增员工功能开发中...')
}

// 查看详情
const handleViewDetail = (staff: StaffVO) => {
  console.log('查看员工详情:', staff)
  ElMessage.info(`查看 ${staff.realName} 的详情`)
}

// 编辑员工
const handleEdit = (staff: StaffVO) => {
  console.log('编辑员工:', staff)
  ElMessage.info(`编辑 ${staff.realName} 的信息`)
}

// 删除员工
const handleDelete = async (staff: StaffVO) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除员工"${staff.realName}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用删除API
    const response = await workStaffApi.deleteStaff(staff.id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      loadStaffList()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除员工失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 工具方法
const getAvatarText = (name: string) => {
  return name ? name.charAt(name.length - 1) : ''
}

const getStatusType = (status: number) => {
  switch (status) {
    case 1: return 'success'
    case 0: return 'danger'
    case 2: return 'warning'
    default: return 'info'
  }
}

const getStatusText = (status: number) => {
  switch (status) {
    case 1: return '在职'
    case 0: return '离职'
    case 2: return '待入职'
    default: return '未知'
  }
}

const formatDate = (date?: string) => {
  if (!date) return '暂无'
  return new Date(date).toLocaleDateString('zh-CN')
}
</script>

<style lang="scss" scoped>
.staff-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 80px);
}

.header-card {
  margin-bottom: 20px;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .header-title {
      h2 {
        margin: 0 0 8px 0;
        font-size: 24px;
        font-weight: 600;
        color: #303133;
      }
      
      p {
        margin: 0;
        color: #909399;
        font-size: 14px;
      }
    }
  }
}

.search-card {
  margin-bottom: 20px;
  
  .status-tabs {
    margin-top: 16px;
    padding-top: 16px;
    border-top: 1px solid #ebeef5;
    
    .status-badge {
      margin-left: 8px;
    }
  }
}

.staff-list-card {
  .empty-state {
    padding: 40px;
    text-align: center;
  }
  
  .staff-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
    gap: 20px;
    margin-bottom: 20px;
  }
  
  .staff-card {
    border: 1px solid #ebeef5;
    border-radius: 8px;
    padding: 20px;
    background: #fff;
    cursor: pointer;
    transition: all 0.3s ease;
    
    &:hover {
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      border-color: #409eff;
    }
    
    .staff-card-header {
      display: flex;
      align-items: center;
      margin-bottom: 16px;
      
      .staff-avatar {
        margin-right: 12px;
      }
      
      .staff-info {
        flex: 1;
        
        .staff-name {
          font-size: 16px;
          font-weight: 600;
          color: #303133;
          margin-bottom: 4px;
        }
      }
    }
    
    .staff-card-body {
      .info-item {
        display: flex;
        margin-bottom: 8px;
        font-size: 14px;
        
        .label {
          width: 80px;
          color: #909399;
          flex-shrink: 0;
        }
        
        .value {
          color: #303133;
          flex: 1;
          
          &.company-name {
            color: #409eff;
            font-weight: 500;
          }
        }
      }
    }
    
    .staff-card-actions {
      margin-top: 16px;
      padding-top: 16px;
      border-top: 1px solid #ebeef5;
      display: flex;
      gap: 8px;
    }
  }
  
  .pagination-wrapper {
    display: flex;
    justify-content: center;
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid #ebeef5;
  }
}
</style>
